use crate::tank::{TankPerception, TankAction, Direction, Point};

pub struct SimpleAI;

impl SimpleAI {
    pub fn decide(perception: &TankPerception) -> TankAction {
        // 如果有敌人，优先攻击最近的敌人
        if !perception.enemies.is_empty() {
            let mut closest_enemy = &perception.enemies[0];
            let mut min_distance = f32::MAX;
            
            for enemy in &perception.enemies {
                let dx = enemy.x - perception.self_state.x;
                let dy = enemy.y - perception.self_state.y;
                let distance = dx * dx + dy * dy;
                
                if distance < min_distance {
                    min_distance = distance;
                    closest_enemy = enemy;
                }
            }
            
            // 如果敌人在攻击范围内，则攻击
            let dx = closest_enemy.x - perception.self_state.x;
            let dy = closest_enemy.y - perception.self_state.y;
            let distance = (dx * dx + dy * dy).sqrt();
            
            if distance <= perception.self_state.attack_range {
                return TankAction::Attack(Point {
                    x: closest_enemy.x,
                    y: closest_enemy.y,
                });
            } else {
                // 否则向敌人移动
                let direction = if distance > 0.0 {
                    if dx.abs() > dy.abs() {
                        if dx > 0.0 {
                            Direction::Right
                        } else {
                            Direction::Left
                        }
                    } else {
                        if dy > 0.0 {
                            Direction::Down
                        } else {
                            Direction::Up
                        }
                    }
                } else {
                    Direction::Up
                };
                
                return TankAction::Move(direction);
            }
        }
        
        // 如果没有敌人，随机移动
        use rand::Rng;
        let mut rng = rand::thread_rng();
        let directions = [Direction::Up, Direction::Down, Direction::Left, Direction::Right];
        let random_direction = directions[rng.gen_range(0..4)];
        
        TankAction::Move(random_direction)
    }
}